import usePermissionStore from '@/stores/permission';
import router from '../index';
import { useLoginStore } from '@/stores/login';
import type { RouteRecordRaw } from 'vue-router';

/**
 * 路由跳转状态
 */
function loading() {
  router.beforeEach((to) => {
    // console.log('跳转中');
    if (to.matched.length) {
      window.$loadingBar?.start();
    }
  });
  router.afterEach((to) => {
    // console.log('跳转完成');
    to.meta.title && (document.title = to.meta.title as string);
    window.$loadingBar?.finish();
  });
  router.onError(() => {
    window.$loadingBar?.error();
  });
}
/**
 * 路由白名单
 */
const whitelist = [
  'login',
  'sso', //'401', '403', '404', '500'
];
/**
 * 权限拦截
 */
function permission() {
  router.beforeEach(async (to, from) => {
    // console.log('to', to, to.name, to.matched, to.fullPath);
    // console.log('from', from);
    /**
     * 验证白名单，若是白名单，直接通过
     */
    if (
      (to.name && whitelist.includes(to.name as string)) ||
      whitelist.includes(to.path)
    ) {
      return true;
    }
    const loginStore = useLoginStore();
    // 获取token
    const token = loginStore.tokenInfo.tokenValue;
    /**
     * 若无token，前往登录页
     */
    if (!token) {
      return {
        name: 'login',
      };
    }
    if (!loginStore.userInfo.account) {
      loginStore.getUserInfo();
    }
    // 获取权限路由
    const permissionStore = usePermissionStore();
    /**
     * 若无权限路由，则获取路由
     */
    if (!permissionStore.permissionMenus.length) {
      await permissionStore.getOriginMenus();
    }
    permissionStore.permissionMenus.forEach((el) => {
      router.addRoute('/', el);
    });

    const routerRecords = router.getRoutes();
    const had = routerRecords.find(
      (el) => el.name === to.name || el.path === to.path,
    );
    if (!had) {
      return { name: '404' };
    }
    // 避免刷新白屏
    if (!to.name) {
      return { name: had.name, replace: true };
    }
    return true;
  });
}

const useGuards = () => {
  loading();
  permission();
};

export { whitelist };

export default useGuards;
